<?php

namespace Xrfg\Api\Trading\Spot\Account\Controllers;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Xrfg\Core\Trading\Account\Models\Coin;
use Xrfg\Core\User\Models\User;
use Xrfg\Core\Trading\Spot\Models\SpotAccount;
use Xrfg\Api\Trading\Spot\Account\Resources\SpotAccountResource;

class SpotAccountController extends Controller
{
    /**
     * 币币账户列表.
     *
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index()
    {
        /** @var User $user */
        $user = Auth::user();
        $coins = Coin::where('is_spot', 1)->get();
        $spotAccounts = SpotAccount::where('user_id', Auth::id())->get();

        // 得到所拥有账户和所有币种的coin_id差集
        $diffIds = array_values(array_diff(
            $coins->pluck('id')->toArray(),
            $spotAccounts->pluck('coin_id')->toArray()
        ));

        // 用户没有的账户创建生成
        foreach ($diffIds as $id) {
            $spotAccount = SpotAccount::firstOrCreate([
                'user_id' => $user->id,
                'coin_id' => $id,
            ]);
            $spotAccounts->push($spotAccount->fresh());
        }

        $coinId = request('coin_id');
        $accountsInfo = SpotAccount::with(['coin' => function ($query) {
            $query->select('id', 'name', 'can_recharge', 'can_withdraw', 'withdraw_min', 'withdraw_max', 'withdraw_fee', 'is_otc', 'is_spot', 'is_tag', 'withdraw_prompt', 'recharge_prompt');
        }])->select('id', 'user_id', 'coin_id', 'available', 'disabled')
        ->where('user_id', $user->id)
        ->when($coinId, function ($query) use ($coinId) {
            $query->where('coin_id', $coinId);
        })
        ->get();

        if ($coinId) { // 单个币种余额
            return new SpotAccountResource($accountsInfo->first());
        } else { // 所有币种余额
            return SpotAccountResource::collection($accountsInfo);
        }
    }
}
